package org.jeecg.modules.lab.entrust.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.lab.entrust.entity.LabEntrustItems;
import org.jeecg.modules.lab.entrust.entity.LabEntrustItemsIndex;
import org.jeecg.modules.lab.entrust.entity.LabEntrustSample;
import org.jeecg.modules.lab.entrust.entity.LabWentrust;
import org.jeecg.modules.lab.entrust.mapper.LabEntrustItemsIndexMapper;
import org.jeecg.modules.lab.entrust.mapper.LabEntrustItemsMapper;
import org.jeecg.modules.lab.entrust.mapper.LabEntrustSampleMapper;
import org.jeecg.modules.lab.entrust.mapper.LabWentrustMapper;
import org.jeecg.modules.lab.entrust.service.ILabWentrustService;
import org.jeecg.modules.lab.entrust.vo.LabEntrustAnaPageA;
import org.jeecg.modules.lab.entrust.vo.LabEntrustAnaPageB;
import org.jeecg.modules.lab.items.entity.*;
import org.jeecg.modules.lab.items.ibasis.mapper.LabItemsBasisMapper;
import org.jeecg.modules.lab.items.ibasis.service.ILabItemsBasisItemsService;
import org.jeecg.modules.lab.items.ibasis.service.ILabItemsBasisService;
import org.jeecg.modules.lab.items.item.mapper.LabItemsBasisIndexMapper;
import org.jeecg.modules.lab.items.item.mapper.LabItemsMapper;
import org.jeecg.modules.lab.items.item.service.ILabItemsService;
import org.jeecg.modules.lab.items.record.service.*;
import org.jeecg.modules.lab.items.relve.service.ILabItemsRelevBasisService;
import org.jeecg.modules.lab.util.FlowNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 委托信息表
 * @Author: jeecg-boot
 * @Date: 2023-07-17
 * @Version: V1.0
 */
@Service
public class LabWentrustServiceImpl extends ServiceImpl<LabWentrustMapper, LabWentrust> implements ILabWentrustService {

    @Autowired
    private LabWentrustMapper labEntrustMapper;

    @Autowired
    private LabEntrustSampleMapper labEntrustSampleMapper;

    @Autowired
    private LabEntrustItemsMapper labEntrustItemsMapper;


    @Autowired
    private LabItemsMapper labItemsMapper;

    @Autowired
    private ILabItemsService labItemsService;

    @Autowired
    private LabItemsBasisMapper labItemsBasisMapper;

    @Autowired
    private ILabItemsRecordSampleService labItemsRecordSampleService;

    @Autowired
    private ILabItemsRecordNormService labItemsRecordNormService;

    @Autowired
    private ILabItemsRecordTargetService labItemsRecordTargetService;

    @Autowired
    private ILabItemsRecordPersonService labItemsRecordPersonService;

    @Autowired
    private ILabItemsRecordDeviceService labItemsRecordDeviceService;

    @Autowired
    private LabItemsBasisIndexMapper labItemsBasisIndexMapper;

    @Autowired
    private LabEntrustItemsIndexMapper labEntrustItemsIndexMapper;

    @Autowired
    private ILabItemsRelevBasisService labItemsRelevBasisService;

    @Autowired
    private ILabItemsBasisService labItemsBasisService;

    @Autowired
    private ILabItemsBasisItemsService labItemsBasisItemsService;

    @Autowired
    private FlowNumberUtil flowNumberUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(LabWentrust labEntrust, List<LabEntrustSample> labSampleList) {

        labEntrustMapper.insert(labEntrust);
        if (labSampleList != null && labSampleList.size() > 0) {
            for (LabEntrustSample entity : labSampleList) {
                //外键设置
                entity.setEntrustId(labEntrust.getId());
                labEntrustSampleMapper.insert(entity);
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(LabWentrust labEntrust, List<LabEntrustSample> labSampleList) throws Exception {

        String executeBasisNum = labEntrust.getExecuteBasisNum();
        String executeBasisId ="";
        if (executeBasisNum != null && !"".equals(executeBasisNum)) {
            LabItemsBasis executeBbasis = labItemsBasisService.getItemsBasis(executeBasisNum);
            if(executeBbasis != null){
                executeBasisId = executeBbasis.getId();
                labEntrust.setExecuteBasisName(executeBbasis.getName());
                labEntrust.setExecuteBasisId(executeBasisId);
            }
        }
        labEntrust.setSynFlag("1");
        labEntrustMapper.updateById(labEntrust);

        String taskId = labEntrust.getId();
        //1.先删除子表数据
        labEntrustSampleMapper.deleteByMainId(taskId);
        labEntrustItemsMapper.deleteByTaskId(taskId);
        labEntrustItemsIndexMapper.deleteByTaskId(taskId);
        labItemsRecordSampleService.deleteByTaskId(taskId);
        labItemsRecordNormService.deleteByTaskId(taskId);
        labItemsRecordTargetService.deleteByTaskId(taskId);
        labItemsRecordPersonService.deleteByTaskId(taskId);
        labItemsRecordDeviceService.deleteByTaskId(taskId);

        //2.子表数据重新插入
        String samId = ""; //样品id
        String samName = "";//样品名称
        String samNum = "";//样品编号
        if (labSampleList != null && labSampleList.size() > 0) {
            for (LabEntrustSample entity : labSampleList) {
                //外键设置
                entity.setEntrustId(labEntrust.getId());
                if ("主剂".equals(entity.getSamType())) {
                    entity.setSamStatus("待检");
                }
                entity.setSynFlag("0");
                entity.setId("");
                labEntrustSampleMapper.insert(entity);
                if ("主剂".equals(entity.getSamType())) {
                    samId = entity.getId();
                    samName = entity.getSamName();
                    samNum = entity.getSamNum();
                }
            }
        }

        //3、委托复审通过实验项目转成项目列表  （该业务逻辑还可以重更新优化调整）
        if ("审核通过".equals(labEntrust.getAuditMark())) {
            String itemsIds = labEntrust.getTestItemsIds().replace("[", "").replace("]", "").replace("\"", "");
            if (itemsIds != null && itemsIds != "") {
                ArrayList listIds = new ArrayList(Arrays.asList(itemsIds.split(",")));
                for (int i = 0; i < listIds.size(); i++) {
                    String item_basis_id = listIds.get(i).toString();
                    ArrayList ids = new ArrayList(Arrays.asList(item_basis_id.split("-")));
                    String item_id = String.valueOf(ids.get(0));
                    String basis_id = "";
                    //兼容历史数据
                    if (ids.size() > 1) {
                        basis_id = String.valueOf(ids.get(1));
                    }

                    //企业标准信息
                    QueryWrapper<LabItemsBasisItems> ItemsBasisQueryWrapper = new QueryWrapper<>();
                    ItemsBasisQueryWrapper.eq("items_id",item_id);
                    ItemsBasisQueryWrapper.eq("basis_id",basis_id);
                    ItemsBasisQueryWrapper.eq("main_basis_id",executeBasisId);
                    LabItemsBasisItems labItemsBasisItems = labItemsBasisItemsService.getOne(ItemsBasisQueryWrapper);

                    if(labItemsBasisItems ==null){
                        throw new Exception("执行标准中缺少配置的实验项目，请配置好再审核！");
                    }

                    LabEntrustItems labEntrustItems = new LabEntrustItems();
                    labEntrustItems.setEntrustId(labEntrust.getId());
                    labEntrustItems.setItemId(item_id);
                    labEntrustItems.setItemName(labItemsBasisItems.getItemsName());
                    //实验项目信息
                    LabItems entity = labItemsMapper.selectById(item_id);
                    labEntrustItems.setTeam(entity.getTeam());
                    labEntrustItems.setPrintMark(entity.getPrintMark());
                    //实验项目标准数据
                    if (basis_id != null && !"".equals(basis_id)) {
                        LabItemsBasis labItemsBasis = labItemsBasisMapper.selectById(basis_id);
                        if (labItemsBasis != null) {
                            labEntrustItems.setBasisId(basis_id);
                            labEntrustItems.setBasisName(labItemsBasis.getName());
                            labEntrustItems.setBasisNum(labItemsBasis.getNum());
                            labEntrustItems.setBasisScope(labItemsBasis.getScope() == null ? "" : labItemsBasis.getScope());
                            labEntrustItems.setBasisAtta(labItemsBasis.getAtta() == null ? "" : labItemsBasis.getAtta());
                        }
                    }

                    labEntrustItems.setBigTypeId(labEntrust.getSampleTypeId());
                    labEntrustItems.setBigTypeName(labEntrust.getSampleType());
                    labEntrustItems.setMidTypeId(labEntrust.getSampleSortId());
                    labEntrustItems.setMidTypeName(labEntrust.getSampleSort());
                    labEntrustItems.setSamId(samId);
                    labEntrustItems.setSamName(samName);
                    labEntrustItems.setSamNum(samNum);
                    if (labItemsBasisItems.getItemsBasisName() == null || "".equals(labItemsBasisItems.getItemsBasisName())) {
                        labEntrustItems.setItemsBasisName(labItemsBasisItems.getItemsName());
                    } else {
                        labEntrustItems.setItemsBasisName(labItemsBasisItems.getItemsBasisName());
                    }

                    labEntrustItems.setItemStatus("待分配");
                    labEntrustItems.setEntrustType("委托检验");
                    labEntrustItems.setSignatureStatus("待同步签名");
                    labEntrustItems.setReportMark("1");
                    labEntrustItems.setSynFlag("0");
                    //添加项目的标准和标准类型
                    labEntrustItemsMapper.insert(labEntrustItems);


                    //增加监测实验指标
                    //根据项目id+标准id查询检测指标，如果没有再根据项目id查询检测指标
                    QueryWrapper<LabItemsBasisIndex> queryWrapper = new QueryWrapper<>();
                    queryWrapper.clear();
                    queryWrapper.eq("items_id", item_id);
                    queryWrapper.eq("basis_id", basis_id);
                    queryWrapper.eq("main_basis_id",executeBasisId);
                    List<LabItemsBasisIndex> labItemsBasisIndexList = labItemsBasisIndexMapper.selectList(queryWrapper);
                    queryWrapper.eq("index_code", "final_value");
                    List<LabItemsBasisIndex> basisIndexs = labItemsBasisIndexMapper.selectList(queryWrapper);
                    if (labItemsBasisIndexList == null) {
                        queryWrapper.clear();
                        queryWrapper.eq("items_id", item_id);
                        queryWrapper.isNull("basis_id");
                        labItemsBasisIndexList = labItemsBasisIndexMapper.selectList(queryWrapper);
                    }

                    if (basisIndexs.size() > 1) {
                        for (LabItemsBasisIndex index : labItemsBasisIndexList) {
                            String indexName = index.getIndexName();
                            if (samName.contains(indexName)) {
                                LabEntrustItemsIndex labEntrustItemsIndex = new LabEntrustItemsIndex();
                                labEntrustItemsIndex.setTaskId(labEntrust.getId());
                                labEntrustItemsIndex.setTaskItemsId(labEntrustItems.getId());
                                labEntrustItemsIndex.setItemId(item_id);
                                labEntrustItemsIndex.setBasisId(basis_id);
//                                labEntrustItemsIndex.setIndexName(index.getIndexName());
                                labEntrustItemsIndex.setIndexCode(index.getIndexCode());
                                labEntrustItemsIndex.setIndexBasis(index.getIndexBasis());
                                labEntrustItemsIndex.setIndexType(index.getIndexType());
                                labEntrustItemsIndex.setSynFlag("0");
                                labEntrustItemsIndexMapper.insert(labEntrustItemsIndex);
                            }
                        }
                    } else {
                        for (LabItemsBasisIndex index : labItemsBasisIndexList) {
                            LabEntrustItemsIndex labEntrustItemsIndex = new LabEntrustItemsIndex();
                            labEntrustItemsIndex.setTaskId(labEntrust.getId());
                            labEntrustItemsIndex.setTaskItemsId(labEntrustItems.getId());
                            labEntrustItemsIndex.setItemId(item_id);
                            labEntrustItemsIndex.setBasisId(basis_id);
                            labEntrustItemsIndex.setIndexName(index.getIndexName());
                            labEntrustItemsIndex.setIndexCode(index.getIndexCode());
                            labEntrustItemsIndex.setIndexBasis(index.getIndexBasis());
                            labEntrustItemsIndex.setIndexType(index.getIndexType());
                            labEntrustItemsIndex.setSynFlag("0");
                            labEntrustItemsIndexMapper.insert(labEntrustItemsIndex);
                        }
                    }


                    //插入项目模板-样品信息
                    labItemsRecordSampleService.insertSamData(labEntrustItems);
                    //插入项目模板-检测条件信息
                    labItemsRecordNormService.insertNormData(labEntrustItems);
                    //插入项目模板-检测信息
                    labItemsRecordTargetService.insertTargetData(labEntrustItems);
                    //插入项目模板-人员信息
                    labItemsRecordPersonService.insertPersonData(labEntrustItems);
                    //插入项目设备-设备信息
                    labItemsRecordDeviceService.insertDeviceData(labEntrustItems);
                }
            }
        }


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSaveMain(LabWentrust labEntrust, List<LabEntrustSample> labSampleList) {

        String sampleType = labEntrust.getSampleType();
        String sampleSort = labEntrust.getSampleSort();
        String testItems = labEntrust.getTestItems();

        // todo 处理大类、类型、项目数据
        if (!"".equals(sampleType) && sampleType != null) {
            QueryWrapper<LabItems> typeWrapper = new QueryWrapper<>();
            typeWrapper.clear();
            typeWrapper.eq("name", sampleType.trim());
            List<LabItems> itemTypes = labItemsService.list(typeWrapper);
            if (itemTypes.size() > 0) {
                String typeId = itemTypes.get(0).getId();
                labEntrust.setSampleTypeId(typeId);
                QueryWrapper<LabItems> sortWrapper = new QueryWrapper<>();
                sortWrapper.clear();
                sortWrapper.eq("name", sampleSort.trim()).eq("pid", typeId);
                List<LabItems> itemSorts = labItemsService.list(sortWrapper);
                if (itemSorts.size() > 0) {
                    String sortId = itemSorts.get(0).getId();
                    labEntrust.setSampleSortId(sortId);
                    if (!"".equals(testItems)) {
                        List<String> itemList = Arrays.asList(testItems.replace('、', ',').split(","));
                        int num = itemList.size();
                        String[] itemsIds = new String[num];
                        String[] itemsNames = new String[num];
                        //todo 找到执行标准下的检测项目
                        String executeBasis = labEntrust.getExecuteBasisNum();
                        LabItemsBasis labItemsBasis = labItemsBasisService.getItemsBasis(executeBasis);
                        if (labItemsBasis != null) {
                            String basisId = labItemsBasis.getId();
                            String basisAtta = labItemsBasis.getAtta();
                            labEntrust.setTestItemsAtta(basisAtta);
                            QueryWrapper<LabItemsBasisItems> basisItemsWrapper = new QueryWrapper<>();
                            basisItemsWrapper.clear();
                            basisItemsWrapper.in("main_basis_id", basisId);
                            List<LabItemsBasisItems> itemsBasisItemsList = labItemsBasisItemsService.list(basisItemsWrapper);
                            int size = itemsBasisItemsList.size();
                            for (int i = 0; i < size; i++) {
                                LabItemsBasisItems itemsBasisItems = itemsBasisItemsList.get(i);
                                String itemNameA = itemsBasisItems.getItemsName();
                                for (String itemNameB : itemList) {
                                    if (itemNameB.trim().equals(itemNameA.trim())) {
                                        String item_id = itemsBasisItems.getItemsId();
                                        String basis_id = itemsBasisItems.getBasisId();
                                        itemsIds[i] = "\"" + item_id + "-" + basis_id + "\"";
                                        itemsNames[i] = "\"" + itemNameA + "\"";
                                    }
                                }
                            }
                        } else {
                            QueryWrapper<LabItems> itemsWrapper = new QueryWrapper<>();
                            itemsWrapper.clear();
                            itemsWrapper.in("name", itemList).eq("pid", sortId);
                            List<LabItems> labItems = labItemsService.list(itemsWrapper);
                            for (int i = 0; i < num; i++) {
                                LabItems item = labItems.get(i);
                                String itemId = item.getId();
                                String itemName = item.getName();
                                QueryWrapper<LabItemsRelevBasis> relevWrapper = new QueryWrapper<>();
                                relevWrapper.clear();
                                relevWrapper.eq("items_id", itemId).eq("core_flag", "1");
                                List<LabItemsRelevBasis> labItemsRelevBasisList = labItemsRelevBasisService.list(relevWrapper);
                                if (labItemsRelevBasisList.size() > 0) {
                                    LabItemsRelevBasis relevBasis = labItemsRelevBasisList.get(0);
                                    String basisId = relevBasis.getBasisId();
                                    itemsIds[i] = "\"" + itemId + "-" + basisId + "\"";
                                    itemsNames[i] = "\"" + itemName + "\"";
                                }
                            }
                        }
                        labEntrust.setTestItemsIds("[" + String.join(",", itemsIds) + "]");
                        labEntrust.setTestItems("[" + String.join(",", itemsNames) + "]");
                    }
                }
            }
        }

        //todo 处理样品信息
        if (labSampleList != null && labSampleList.size() > 0) {
            int zNum = 0;
            int fNum = 0;
            for (LabEntrustSample entity : labSampleList) {
                String samType = entity.getSamType();
                if ("主剂".equals(samType)) {
                    entity.setSamNum(flowNumberUtil.generateSerialNum("WXY", 1).get(0));
                    zNum++;
                } else {
                    fNum++;
                }
            }
            labEntrust.setSampleNum(zNum);
            labEntrust.setSampleCount(zNum);
            if (fNum > 0) {
                labEntrust.setAuxiliarySample("1");
                labEntrust.setAuxiliaryNum(fNum);
            } else {
                labEntrust.setAuxiliarySample("0");
            }
        }
        labEntrust.setHandlDate(DateUtils.getDate("YYYY-MM-dd"));
        if (labEntrust.getSampleDate() != null) {
            labEntrust.setSampleDate(DateUtils.dateformat(labEntrust.getSampleDate().replace(".", "-").replace("/", "-").replace("_", "-"), "YYYY-MM-dd"));
        }
        int zNum = 0;
        int fNum = 0;
        for (LabEntrustSample entity : labSampleList) {
            String samType = entity.getSamType();
            if ("主剂".equals(samType)) {
                zNum++;
            } else if ("辅剂".equals(samType)) {
                fNum++;
            }
        }
        labEntrust.setSampleCount(zNum);
        labEntrust.setAuxiliarySample(fNum > 0 ? "1" : "0");
        labEntrust.setAuxiliaryNum(fNum);
        labEntrust.setAuditMark("制单中");
        labEntrust.setAllotStatus("未分配");
        labEntrust.setCodeRule("WXY");
        labEntrust.setEntrustType("委托检验");
        labEntrust.setCarryName("中国石油西南油气田分公司天然气研究院气田开发化学实验室");
        labEntrust.setCarryAddress("四川省成都市天府新区华阳天研路218号610213");
        labEntrust.setCarryContact("印 敬/(028)85604123 13880486175 张楠革/(028)85604594 13618090676");
        labEntrust.setSynFlag("0");
        labEntrustMapper.insert(labEntrust);
        if (labSampleList != null && labSampleList.size() > 0) {
            for (LabEntrustSample entity : labSampleList) {
                //外键设置
                String samName = entity.getSamName();
                if(samName!=null && !"".equals(samName)){
                    entity.setEntrustId(labEntrust.getId());
                    if (entity.getSamDate() != null) {
                        entity.setSamDate(DateUtils.dateformat(entity.getSamDate().replace(".", "-").replace("/", "-").replace("_", "-"), "YYYY-MM-dd"));
                    }
                    entity.setSynFlag("0");
                    labEntrustSampleMapper.insert(entity);
                }

            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        labEntrustSampleMapper.deleteByMainId(id);
        labEntrustMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            labEntrustMapper.deleteById(id);
        }
    }

    @Override
    public void updateEntStatusById(String id, String auditMark, String nameStr) {
        labEntrustMapper.updateEntStatusById(id, auditMark, nameStr);
    }

    @Override
    public LabEntrustAnaPageA queryEntrustYCount() {

        String year = DateUtils.getDate("yyyy");
        return labEntrustMapper.queryEntrustYCount(year);
    }

    @Override
    public List<LabEntrustAnaPageB> queryEntrustMCount() {
        String yearM = DateUtils.getDate("yyyy-MM");
        String year = DateUtils.getDate("yyyy");
        return labEntrustMapper.queryEntrustMCount(year, yearM);
    }

    @Override
    public List<LabWentrust> getAuditList(String auditMark, String entName, String handler, String handlDate, String sampleType, String userId,String userName) {
        return labEntrustMapper.getAuditList(auditMark, entName, handler, handlDate, sampleType, userId,userName);
    }

    /**
     * 更新用户签名
     */
    @Override
    public void updatasz(String ides, String encodedUrl) {
        labEntrustMapper.updatasz(ides, encodedUrl);
        //labEntrustMapper.updatasz(user.getId());
    }

    /**
     * 获取用户列表
     *
     * @return
     */
    @Override
    public List<LoginUser> getUserList() {
        return labEntrustMapper.getUserList();
    }

    @Override
    public LoginUser getOneUser(String id) {
        return labEntrustMapper.getOneUser(id);
    }

    @Override
    public LoginUser byLoginUser(Integer employeeId) {
        return labEntrustMapper.byLoginUser(employeeId);
    }

}
